# encoding: utf-8
# @File  : task.py
# @Author: shaoyun
# @Date  :  2025/05/11
import enum
from datetime import datetime

from sqlalchemy import Column, Integer, String, DateTime, Text, Enum, ForeignKey, Float
from sqlalchemy.orm import relationship

from app.db.mysql import Base


class TaskStatus(enum.Enum):
    """任务状态枚举"""
    PENDING = "pending"  # 等待执行
    RUNNING = "running"  # 正在执行
    COMPLETED = "completed"  # 执行完成
    FAILED = "failed"  # 执行失败
    CANCELED = "canceled"  # 已取消


class Task(Base):
    """任务模型"""
    __tablename__ = "tasks"

    id = Column(String(36), primary_key=True, index=True)
    user_id = Column(String(36), ForeignKey("users.id"), nullable=False)
    spider_id = Column(String(36), nullable=False, index=True)  # 关联爬虫
    name = Column(String(255), nullable=False)  # 任务名称
    parameters = Column(Text, nullable=False, default="{}")  # JSON格式的参数
    status = Column(Enum(TaskStatus), default=TaskStatus.PENDING, index=True)  # 任务状态
    priority = Column(Integer, default=0, index=True)  # 任务优先级
    cron = Column(String(100), nullable=True)  # Cron表达式，用于定时任务

    created_at = Column(DateTime, default=datetime.utcnow, index=True)  # 创建时间
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)  # 更新时间
    started_at = Column(DateTime, nullable=True)  # 开始时间
    finished_at = Column(DateTime, nullable=True)  # 结束时间

    # 关联
    user = relationship("User", back_populates="tasks")
    nodes = relationship("TaskNodeAssociation", back_populates="task")

    def __repr__(self):
        return f"<Task {self.id}: {self.name}>"


class TaskNodeAssociation(Base):
    """任务与节点的关联表"""
    __tablename__ = "task_node"

    task_id = Column(String(36), ForeignKey("tasks.id"), primary_key=True)
    node_id = Column(String(36), ForeignKey("nodes.id"), primary_key=True)
    assigned_at = Column(DateTime, default=datetime.utcnow)

    # 定义关系
    task = relationship("Task", back_populates="nodes")
    node = relationship("Node", back_populates="tasks")